<template>
  <el-container>
    <!-- <RegionTree style="margin-top: 16px" @on-choose-region="filetrRegion" /> -->
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="['refresh', 'comSearch', 'columnDisplay']"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import { ref, provide, onMounted, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { EquipMCarbon } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useCarbon } from "@/store/backend/EquipM/activeCarbon";
import { useRouter, useRoute } from "vue-router";
import type { TableColumn, TableRow } from "@/utils/baTable"; //表格列行类型
// import RegionTree from "@/components/roleRegionTree/index.vue";
import { useRegion } from "@/store/backend/SysM/region";
import Cascader from "@/components/Cascader/index.vue";
import TagState from "@/components/dictTagState/index.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import { useNavTabs } from "@/store/navTabs";
import { useAccess } from "@/store/backend/DeviceM/access";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const carbon = useCarbon();
const router = useRouter();
const route = useRoute();
const region = useRegion();
const dictionary = useDictionary();
const access = useAccess();
const navTabs = useNavTabs();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + EquipMCarbon)
      ? (navTabs as any).pageSizeMap.get(route.path + EquipMCarbon)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(EquipMCarbon), //this.api = api菜单管理相关
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("ecode"),
        label: "设备编号",
        prop: "ecode",
        align: "center",
      },
      { label: "关联企业", width: "240", prop: "cname", align: "center" },
      {
        show: filedShowOff("state"),
        label: "设备状态",
        prop: "state",
        align: "center",
        width: "90",
        render: "customRender",
        customRender: markRaw(TagState),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("life"),
        label: "活性炭",
        prop: "life",
        align: "center",
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          return "<p>" + value + " %" + "</p>";
        },
      },
      {
        show: filedShowOff("timeNum"),
        label: "累计运行时长(时)",
        prop: "timeNum",
        align: "center",
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          return "<p>" + (value / 3600).toFixed(2) + "" + "</p>";
        },
      },
      {
        show: filedShowOff("replaceNum"),
        label: "更换滤芯次数",
        prop: "replaceNum",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("pressureValue"),
        label: "压力初始值",
        prop: "pressureValue",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("createTime"),
        label: "投用日期",
        prop: "createTime",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("replaceTime"),
        label: "最新更换滤芯时间",
        prop: "replaceTime",
        align: "center",
        operator: false,
      },
      {
        show: false,
        label: "选择区域",
        prop: "",
        align: "center",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(Cascader),
      },
      // { label: "压力告警值", prop: "criticalValue", align: "center" },
      // { label: "使用寿命长度", prop: "lifeValue", align: "center" },
      {
        show: operatorShowOff([route.path + "/edit"]),
        label: "操作",
        align: "center",
        width: "120",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "详情",
            text: "",
            type: "primary",
            icon: "iconfont icon-chaxunyujisuan",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: {
      regions: region.regionIds + "",
      pageSize: pageSizeKeep(),
    },
  }
);
type Carbon = {
  createBy: null;
  createTime: string;
  createUser: null;
  criticalValue: number;
  ecode: string;
  eid: number;
  id: number;
  life: null;
  lifeValue: number;
  params: anyObj;
  pressureValue: number;
  remark: null;
  replaceNum: null;
  replaceTime: null;
  searchValue: null;
  state: null;
  timeNum: null;
  updateBy: null;
  updateTime: null;
};
interface Region {
  address: string | null;
  addressDetail: string | null;
  areaFlag: string | null;
  areaId: number;
  areaName: string | null;
  areaNo: string | null;
  children: Region[];
  createBy: string | null;
  createTime: string | null;
  endTime: string | null;
  params: any;
  parentId: number;
  searchValue: string | null;
  startTime: string | null;
  updateBy: string | null;
  updateTime: string | null;
}
// const filetrRegion = (row: Region, node: any) => {
//   //判断node属性中checkedNodes是否为空
//   if (node.checkedKeys.length == 0) {
//     //表示取消选择直接调用刷新表单方法
//     baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
//       regions: region.regionIds + "",
//     });
//     baTable.onTableHeaderAction("refresh", {});
//   } else {
//     baTable.comSearch.form.regions = node.checkedKeys + "";
//     baTable.getList(EquipMCarbon);
//   }
// };
//活性炭数据监控
const infoButtonClick = (name: string, item: any) => {
  console.log("活性炭数据监控", item);
  access.getDevicesItem(item.eid).then((res: any) => {
    console.log("获取网关编号", res);
    carbon.gatewaycode = res.data.gatewaycode;
    carbon.$patch((state) => {
      state.item = item;
    });
    router.push({ path: "/admin/EquipM/carBondetail", query: {} });
  });
};
type RootObject = {
  equipid: number;
  name: string;
  avatar: string;
  owner_auth: number;
  user_auth: number;
  remark: string;
  is_online: number;
  is_alarm: number;
  is_running: number;
  status: string;
  last_parser_time: number;
  wind_speed: string;
  temperature: string;
  pa: string;
  carbonUse: string;
  dev_name: string;
  current_value_sensorid: number;
  current_value_updatetime: number;
  tags: any[];
};

//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("device_online_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  //   console.log("tableRef.value", tableRef.value);
  baTable.mount();
  baTable.getList(EquipMCarbon);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: Carbon | TableRow }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "edit") {
        console.log("edit", data.row);

        // 主键字段 pk: "name",
        infoButtonClick((data.row as TableRow).id, data.row as Carbon);
      }
    }
  );
});

// 相当于表格的onMounted，也可以在页面的onMounted时执行
// baTable.mount();
// 获取数据，可以在页面的onMounted时执行，也可以比如先请求一个API，再执行获取数据
// baTable.getIndex("menuData");//前置调用
//baTable.getIndex()!.then(() => {
//查看请求完毕（已获取到表格数据）
//  baTable.initSort() // 初始化默认排序（如果需要）
//  baTable.dragSort() // 初始化拖拽排序（如果需要）
//})

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
.el-main {
  padding: 0;
}
</style>
